package com.dzh.dzhhub.shiro.jwt;

/**
 * @author DZHooo
 * @version 1.0
 * @date 2021/11/17 21:36
 * @description: TODO
 */

import com.dzh.dzhhub.util.Base64ConvertUtil;
import com.dzh.dzhhub.util.JwtUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.io.UnsupportedEncodingException;


public class JwtCredentialsMatcher implements CredentialsMatcher {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * JWT认证加密私钥(Base64加密)
     */
    private static String encryptJWTKey = "U0JBUElKV1RkV2FuZzkyNjQ1NA==";

//    @Value("${encryptJWTKey}")
//    public void setEncryptJWTKey(String encryptJWTKey) {
//        JwtUtils.encryptJWTKey = encryptJWTKey;
//    }

    /**
     * JwtCredentialsMatcher只需验证JwtToken内容是否合法
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {

        String token = authenticationToken.getCredentials().toString();
        String username = authenticationToken.getPrincipal().toString();
        String secret = null;
        try {
            secret = username + Base64ConvertUtil.decode(encryptJWTKey);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

}
